package com.kkm.service.Imp;

import com.kkm.dao.BrandDao;
import com.kkm.dao.Imp.BrandDaoImp;
import com.kkm.pojo.Brand;
import com.kkm.pojo.PageBean;
import com.kkm.service.BrandService;

import java.util.List;

public class BrandServiceImp implements BrandService {
    private BrandDao brandDao=new BrandDaoImp();
    @Override
    public PageBean<Brand> showBrand(String currentPage , int rows) {
        int currPage=Integer.parseInt(currentPage);
        if(currPage<=0){
            currPage=1;
        }
        PageBean<Brand> pageBean=new PageBean(); //实例化pagebean对象
        int count=brandDao.checkCount();        //查询记录数

        int totalPage=count%rows==0?count/rows :count/rows+1;
        if(currPage>=totalPage){
            currPage=totalPage;
        }

        int index=(currPage-1)*rows;
        List<Brand> brands=brandDao.showBrand(index,rows);

        pageBean.setRows(rows);
        pageBean.setCurrentPage(currPage);
        pageBean.setTotalPage(totalPage);
        pageBean.setTotalCount(count);
        pageBean.setList(brands);

        return pageBean;

    }

    @Override
    public int addBrand(String bname) {
        int num=0;
        num=brandDao.checkCount(bname);
        if(num==0){
            brandDao.addBrand(bname);
            return 1;
        }else {
            return 0;
        }
    }

    @Override
    public PageBean<Brand> checkBrand(String checkName, String currentPage, int rows) {
        int currPage=Integer.parseInt(currentPage);
        if(currPage<=0){
            currPage=1;
        }
        PageBean<Brand> pageBean=new PageBean(); //实例化pagebean对象
        int count=brandDao.checkCount(checkName);        //查询记录数
        if(count>=1){
            int totalPage=count%rows==0?count/rows :count/rows+1;
            if(currPage>=totalPage){
                currPage=totalPage;
            }

            int index=(currPage-1)*rows;
            List<Brand> brands=brandDao.checkBrand(checkName,index,rows);
            pageBean.setRows(rows);
            pageBean.setCurrentPage(currPage);
            pageBean.setTotalPage(totalPage);
            pageBean.setTotalCount(count);
            pageBean.setList(brands);
            return pageBean;
        }
        return null;
    }

    @Override
    public void deleteBrand(String bid) {
        int id=Integer.parseInt(bid);
        brandDao.deleteBrand(id);
    }

    @Override
    public int modifyBrand(String bid, String newName) {
        int num=0;
        num=brandDao.checkCount(newName);
        if(num==0){
            int id=Integer.parseInt(bid);
            brandDao.modifyBrand(newName,id);
            return 1;
        }else {
            return 0;
        }
    }
}
